package com.qipa.netty.handler;

import com.qipa.netty.heartbeat.ChannelMapObject;
import com.qipa.netty.heartbeat.NettyChannelMap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerHeartBeatHandler extends ChannelInboundHandlerAdapter {

    private final static Logger logger = LoggerFactory.getLogger(ServerHeartBeatHandler.class);

    private static final int MAX_UN_REC_HEARTBEAT_TIME = 3;//多少次没收到心跳才真正回收连接，第四次才会真正回收连接

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        logger.info("已经挺久未收到客户端的消息了！");
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                handleReaderIdle(ctx);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        logger.info("read heartBeat from client {}", msg.toString());
        //交给下一个处理器
        ctx.fireChannelRead(msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //客户端连上以后把回话存起来
        SocketChannel channel = (SocketChannel) ctx.channel();
        String id = channel.id().asLongText();
        ChannelMapObject object = new ChannelMapObject(channel);
        NettyChannelMap.add(id, object);
        super.channelActive(ctx);
    }

    private void handleReaderIdle(ChannelHandlerContext ctx) {
        ChannelMapObject object = NettyChannelMap.getMapObject((SocketChannel) ctx.channel());
        if (null != object) {
            if (object.getLostHeartBeatCount() >= MAX_UN_REC_HEARTBEAT_TIME) {
                //删除保存的会话
                NettyChannelMap.remove((SocketChannel) ctx.channel());
                logger.error("Close channel by heart beat, IP:" + ctx.channel().remoteAddress());
            } else {
                object.plusLostCount();
                logger.info("Un receive heartbeat request, count:" + object.getLostHeartBeatCount());
            }
        }

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
    }
}
